package com.stars.easyms.datasource;

import org.springframework.jdbc.datasource.AbstractDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * <p>className: AbstractRoutingDataSource</p>
 * <p>description: 多数据源路由抽象类</p>
 *
 * @author guoguifang
 * @version 1.1.0
 * @date 2019-03-05 15:28
 */
abstract class AbstractRoutingDataSource extends AbstractDataSource {

    @Override
    public Connection getConnection() throws SQLException {
        return this.determineDataSource().getConnection();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return this.determineDataSource().getConnection(username, password);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T unwrap(Class<T> iface) throws SQLException {
        if (iface.isInstance(this)) {
            return (T) this;
        }
        return this.determineDataSource().unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return (iface.isInstance(this) || this.determineDataSource().isWrapperFor(iface));
    }

    /**
     * 决定使用哪个数据源
     *
     * @return 数据源
     */
    protected abstract DataSource determineDataSource();
}